package com.ecarx.common;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.multidex.MultiDex;

import com.ecarx.common.utils.ActivityControl;

public class BaseApplication extends Application implements ViewModelStoreOwner {
    public static BaseApplication bApp;
    protected ActivityControl mActivityControl;
    private ViewModelStore mAppViewModelStore;
    private ViewModelProvider.Factory mFactory;
    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return mAppViewModelStore;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        bApp = this;
        MultiDex.install(this);
        mActivityControl =new ActivityControl();
        mAppViewModelStore = new ViewModelStore();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                mActivityControl.addActivity(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                mActivityControl.removeActivity(activity);
            }
        });
       new  CrashHandler().init();
    }

    public ViewModelProvider  getAppViewModelProvider(){
        return new ViewModelProvider(
                bApp,
                bApp.getAppFactory()
        );
    }

    private ViewModelProvider.Factory getAppFactory() {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(bApp);
        }
        return mFactory;
    }
    public ActivityControl getActivityControl(){
        return mActivityControl;
    }
}
